package net.example.model;
import com.oraycn.omcs.utils.BufferUtils;
import com.oraycn.omcs.utils.SerializeUtils;
import net.example.model.common.RichChatMessage;
import net.example.utils.SerializeHelper;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;

public class SnapchatMessage
{
    public SnapchatMessage() { }
    public SnapchatMessage(String id, String creator, RichChatMessage message)
    {
        this.ID = id;
        this.CreatorID = creator;
        this.ChatBoxContent = message;
    }

    /**
     * 消息编号。
     * */
    public String ID ;

   /**
    * 短信创建者的ID。
    * */
    public String CreatorID ;

    /**
     * 内容数据列表。
     * */
    public RichChatMessage ChatBoxContent ;

    /**
     * 携带的数据。
     * */
    public String Tag ="";

    /**
     * 获取唯一编号。CreatorID - ID
     * */
    public String GetUniqueID()
    {
        return this.CreatorID + "-" + this.ID;
    }

    public void deserialize(byte[] info) throws Exception {
        ByteBuf buffer = SerializeHelper.wrappedBuffer(info);
        buffer.readInt();
        RichChatMessage message=new RichChatMessage();
        message.deserialize(buffer);
        this.ChatBoxContent= message;
        this.CreatorID=SerializeUtils.readStrIntLen(buffer);
        this.ID=SerializeUtils.readStrIntLen(buffer);
        this.Tag=SerializeUtils.readStrIntLen(buffer);
    }


    public byte[] serialize() throws Exception {
        byte[] bChatBoxContent = ChatBoxContent.serialize();
        byte[] bCreatorID = CreatorID.getBytes(StandardCharsets.UTF_8);
        byte[] bID= ID.getBytes(StandardCharsets.UTF_8);
        byte[] bTag= Tag.getBytes(StandardCharsets.UTF_8);

        int contractLen = bChatBoxContent.length+4 + bCreatorID.length + 4 + bID.length +4+bTag.length ;
        ByteBuf body = BufferUtils.newBuffer();
        body.writeInt(contractLen);
       // body.writeInt(bChatBoxContent.length);
        body.writeBytes(bChatBoxContent);
//        body.writerIndex(bChatBoxContent.length);
        body.writeInt(bCreatorID.length);
        body.writeBytes(bCreatorID);
        body.writeInt(bID.length);
        body.writeBytes(bID);
        body.writeInt(bTag.length);
        body.writeBytes(bTag);
        byte[] result = new byte[body.readableBytes()];
        System.arraycopy(body.array(),0,result,0,result.length);
        return result;
    }

}

